package com.ruoyi.project.emmanuel.account.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ToolUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.emmanuel.account.domain.AccountAccount;
import com.ruoyi.project.emmanuel.account.domain.AccountBill;
import com.ruoyi.project.emmanuel.account.domain.AccountClass;
import com.ruoyi.project.emmanuel.account.service.IAccountAccountService;
import com.ruoyi.project.emmanuel.account.service.IAccountBillService;
import com.ruoyi.project.emmanuel.account.service.IAccountClassService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 账单统计Controller
 *
 * @author ruoyi
 * @date 2022-01-23
 */
@Controller
@RequestMapping("/account/bill")
public class AccountBillController extends BaseController {

    private String prefix = "emmanuel/account/bill";

    @Autowired
    private IAccountBillService accountBillService;
    @Autowired
    private IAccountAccountService accountAccountService;
    @Autowired
    private IAccountClassService accountClassService;

    @RequiresPermissions("account:bill:view")
    @GetMapping()
    public String bill(ModelMap modelMap) {
        // 返回账本
        List<AccountAccount> accountList = accountBillService.getAccount();
        modelMap.put("accountList", accountList);
        return prefix + "/bill";
    }

    /**
     * 查询账单统计列表
     */
    @RequiresPermissions("account:bill:view")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AccountBill accountBill) {
        startPage();
        List<AccountBill> list = accountBillService.countMoneyByMonth(accountBill);
        return getDataTable(list);
    }

    /**
     * 导出账单统计列表
     */
    @RequiresPermissions("account:bill:export")
    @Log(title = "导出账单统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AccountBill accountBill) {
        List<AccountBill> list = accountBillService.countMoneyByMonth(accountBill);
        ExcelUtil<AccountBill> util = new ExcelUtil<AccountBill>(AccountBill.class);
        return util.exportExcel(list, "账单统计数据");
    }


    /**
     * 查看更多按钮（跳转到统计页面）
     *
     * @param modelMap
     * @param month
     * @return
     */
    @GetMapping("/bullCount/{id}")
    @RequiresPermissions("account:bill:count")
    public String billConuntPage(ModelMap modelMap, @PathVariable(value = "id") String month) {

        List<Map<String,Object>> accountDetailList = accountBillService.accountDetailByMonth(month);

        // 收入
        List<Map<String, Object>> incomeList = accountDetailList.stream().filter(accountMoney -> Objects.equals("1", accountMoney.get("status"))).collect(Collectors.toList());
        // 支出
        List<Map<String, Object>> payList = accountDetailList.stream().filter(accountMoney -> Objects.equals("2", accountMoney.get("status"))).collect(Collectors.toList());
        // 不计入
        List<Map<String, Object>> moneyIgnoreList = accountDetailList.stream().filter(accountMoney -> Objects.equals("3", accountMoney.get("status"))).collect(Collectors.toList());

        modelMap.put("month", month);
        modelMap.put("incomeList", incomeList);
        modelMap.put("payList", payList);
        modelMap.put("moneyIgnoreList", moneyIgnoreList);
        return prefix + "/count";
    }

    /**
     * 统计页面的请求
     *
     * @param modelMap
     * @param month    月
     * @return
     */
    @GetMapping("/bullCount/month")
    @ResponseBody
    @RequiresPermissions("account:bill:count")
//    @Log(title = "查询月账单图形统计")
    public HashMap<String, Object> billConunt(ModelMap modelMap, String month) {
        return accountBillService.billConunt(month);
    }

    @GetMapping("/bullCount/billCalendarByMonth")
    @ResponseBody
    @RequiresPermissions("account:bill:count")
    public JSONObject billCalendarByMonth(ModelMap modelMap, String month) {
        JSONObject js = accountBillService.fullCalendarList(month);
        return js;
    }

    /**
     * 记账账户分析
     */
    @RequiresPermissions("account:account:analysis")
    @GetMapping("/accountAnalysis/{accountId}")
    @ResponseBody
    public Map<String, Object> accountAnalysis(@PathVariable("accountId") Long accountId, ModelMap modelMap) {
        Map<String, Object> map = accountBillService.accountAnalysis(accountId, modelMap);
        return map;
    }

    /**
     * 记账账户分析 - 查询指定账户近期收支情况
     */
    @RequiresPermissions("account:account:analysis")
    @GetMapping("/accountAnalysisByMonth/{accountId}")
    @ResponseBody
    public Map<String, Object> accountAnalysisByMonth(@PathVariable("accountId") Long accountId, ModelMap modelMap) {
        Map<String, Object> map = accountBillService.accountAnalysisByMonth(accountId, modelMap);
        return map;
    }

    /**
     * 统计页面的请求
     *
     * @param modelMap
     * @param month    月
     * @return
     */
    @GetMapping("/bullCount/moneyByMonth")
    @ResponseBody
    @RequiresPermissions("account:bill:count")
    public Map<String, Object> billCountByMonth(ModelMap modelMap, String month) {
        return accountBillService.billCountByMonth(month);
    }

    /**
     * 分类月账单
     */
    @Log(title = "分类月账单", businessType = BusinessType.SELECT)
    @PostMapping("/selectMoneyByClass")
    @ResponseBody
    public AjaxResult selectMoneyByClass(AccountAccount accountAccount) {

        // 获取分类数据
        AccountClass accountClass = new AccountClass();
        Map<String, Object> params = new HashMap<>();
        params.put("accountId", accountAccount.getId());
        accountClass.setParams(params);
        List<AccountClass> accountClassesList = accountClassService.selectAccountClassListByAccountId(accountClass);

        // 存放表头和数据的
        Map<String, Object> map = new HashMap<>();


        if (ToolUtils.isEmpty(accountClassesList)) {
            return AjaxResult.success("操作成功", map);
        }

        map = accountClassService.selectMoneyByClass(accountAccount,accountClassesList);

        return AjaxResult.success("操作成功", map);
    }


    /**
     * 按月-日显示详情
     *
     * @param modelMap 视图模型
     * @param month    2025-03
     * @return
     */
    @GetMapping("/monthBill/{id}")
    @RequiresPermissions("account:month:bill:count")
    public String monthBill(ModelMap modelMap, @PathVariable(value = "id") String month) {

        // 根据天分组
        List<Map<String, Object>> moneyGroupByDayList = accountBillService.queryMoneyGroupByDay(month);

        // 获取月账单详情
        List<Map<String, Object>> accountDetailList = accountBillService.accountDetailByMonth(month);

        // 按天分组组织数据
        moneyGroupByDayList.forEach(m -> {
            List<Map<String, Object>> montyListByDay = accountDetailList.stream().filter(k -> StringUtils.equals(String.valueOf(m.get("moneyDate")), String.valueOf(k.get("moneyDate")))).collect(Collectors.toList());
            m.put("montyListByDay", montyListByDay);
        });

        // 总收入/总支出/总不计入
        accountAccountService.getBillTotal(modelMap, accountDetailList);

        // 展示页面数据
        modelMap.put("month", month);
        modelMap.put("moneyGroupByDay", moneyGroupByDayList);

        // 展示页面
        return prefix + "/month-bill";
    }


}
